import {
	useUserInfoStore
} from "@/stores/modules/user.js"

// #ifdef MP-WEIXIN
const BASE_URL = 'http://localhost:8081/api';
// const BASE_URL = 'http://192.168.68.84:8081/api';
// #endif

// #ifdef H5
const BASE_URL = '/api';
// #endif


export function request(config = {}) {

	const userTokenInfo = useUserInfoStore();
	// 默认的请求头
	const defaultHeader = {
		"Content-Type": "application/json;charset=utf-8"
	}

	let {
		url,
		data = {},
		method = "GET",
		header = {
			...defaultHeader
		}
	} = config
	// 拼接的路径是正常的
	url = BASE_URL + url
	// console.log("token信息", userTokenInfo);
	if (userTokenInfo.tokenInfo) {
		header['satoken'] = userTokenInfo.tokenInfo
	}
	// header["Content-Type"] = "application/json;charset=utf-8"

	return new Promise((resolve, reject) => {

		uni.request({
			url,
			data,
			method,
			header,
			success: res => {
				console.log("res:", res);
				if (res.data.code === 200) {
					resolve(res.data)
				} else if (res.data.code === 500) {
					uni.showModal({
						title: "错误提示",
						content: res.data.msg,
						sdhowCancel: false
					})
					reject(res.data)
				} else if (res.data.code === 401 || res.statusCode === 401) {
					let redirectUrl = '';
					// 记录访问前的页面地址，登陆后重定向到那个页面
					let routes = getCurrentPages() //获取当前页面栈
					redirectUrl = routes[routes.length - 2].route //获取当前页面的路由
					console.log('页面路由：', redirectUrl);
					uni.showToast({
						title: "登录身份失效！",
						icon: "error"
					})
					setTimeout(() => {
						uni.navigateTo({
							url: "/pages/user/login?redirect=" + redirectUrl
						})
					}, 500)
				} else if (res.data === '' && res.statusCode === 200) {
					resolve()
				} else {
					uni.showToast({
						title: res.data?.msg || "请求失败",
						icon: "none"
					})
					reject(res.data)
				}
			},
			fail: err => {
				uni.showModal({
					title: "错误提示",
					content: res.data.msg,
					showCancel: false
				})
				console.log("未登录！！！");
				reject(err)
			}
		})
	})
}


// 通用文件上传方法
export function uploadFile(filePath) {
	const userTokenInfo = useUserInfoStore();

	// 默认的请求头 添加token
	const defaultHeader = {
		'satoken': `${userTokenInfo.tokenInfo}`,
		"Content-Type": "multipart/form-data"
	}

	return new Promise((resolve, reject) => {
		uni.uploadFile({
			header: {
				...defaultHeader
			},
			url: BASE_URL + "/file/upload",
			filePath: filePath,
			name: "file",
			method: "POST",
			success: (res) => {
				// console.log("文件返回信息：", res);
				// 上传成功后，获取返回的文件路径
				if (res.statusCode == 200) {
					// json解析
					let resData = JSON.parse(res.data)
					resolve(resData)
				} else {
					uni.showToast({
						title: "上传失败！",
						icon: "none"
					})
					reject(res)
				}
			},
			fail: (err) => {
				console.log("文件上传失败返回信息：", res);
				uni.showToast({
					title: "上传失败",
					icon: "none"
				})
				reject(err)
			}
		})
	})
}